import "@ethersproject/shims";
import { ethers } from 'ethers';
import { global } from "@/config/config";

const httpsProvider = new ethers.providers.JsonRpcProvider(global.ethrpcurl);

const getTransferERC721ABI = (from, to, tokenId) => {
    const ABI = ["function safeTransferFrom(address from, address to, uint256 tokenId)"]
    const masterIface = new ethers.utils.Interface(ABI);
    const masterAbi = masterIface.encodeFunctionData("safeTransferFrom", [from, to, tokenId]);
    return masterAbi;
}

const estimateGasForTransferERC721 = async (from, to, tokenId) => {
    const data_ = getTransferERC721ABI(from, to, tokenId);
    const estimateGas = await httpsProvider.estimateGas({
        from: from,
        to: global.ERC721ContractAddress,
        data: data_
    })
    return estimateGas;
}

const transferERC721 = async (privateKey, from, to, tokenId) => {
    const wallet = new ethers.Wallet(privateKey);
    const address = wallet.address
    const inputData = getTransferERC721ABI(from, to, tokenId);
    const nonce = await httpsProvider.getTransactionCount(address);
    const feeData = await httpsProvider.getFeeData();
    const gasConsume = await estimateGasForTransferERC721(from, to, tokenId);
    const totalFee = ethers.utils.formatUnits(feeData["maxFeePerGas"] * gasConsume, 'ether');
    const tx = {
        type: 2,
        nonce: nonce,
        to: global.ERC721ContractAddress, // Address to send to
        maxPriorityFeePerGas: feeData["maxPriorityFeePerGas"], // Recommended maxPriorityFeePerGas
        maxFeePerGas: feeData["maxFeePerGas"], // Recommended maxFeePerGas
        value: "0x0",
        gasLimit: gasConsume,
        data: inputData,
        chainId: 5,
    };
    const signedTx = await wallet.signTransaction(tx);
    //交易Hash
    // const txHash = ethers.utils.keccak256(signedTx);
    httpsProvider.sendTransaction(signedTx);
    await transaction.wait();
}

// transferERC721("0xD6F71F96e2791Cfd5F94bC58590eaad53DEcc2E6", "0x96364ccAadECB79b5ffde7F9d2032a28217e7069", 3);